<script setup lang="ts">
import type { CustomDialogInstance } from '@/types/modules/public'
import { importMeasuringTools, getMeasuringToolsTemplate } from '@/api/modules/measuringTools'

const emits = defineEmits<{
  (e: 'afterClose'): void
}>()

const dialogRef = ref<CustomDialogInstance>()
const inputRef = ref<HTMLInputElement>()
const file = ref<File>()
const msgs = ref<string[]>([])
const isOk = ref(false)
const uploadable = computed(() => {
  return !!file.value
})
const uploading = ref(false)

async function changeInput(e: Event) {
  const target = e.target as HTMLInputElement
  const files = target.files
  if (files) {
    const f = files[0]
    file.value = f
  }
}
async function clickImportFile() {
  if (file.value) {
    try {
      uploading.value = true
      const { data } = await importMeasuringTools(file.value)
      msgs.value = data
      isOk.value = !data || data.length === 0
    }
    finally {
      uploading.value = false
    }
  }
  else {
    msgs.value = []
  }
}
async function clickExportFile() {
  await getMeasuringToolsTemplate()
}

function onClose() {
  // 关闭弹框后将file置空
  // input 元素会自动删除
  // msgs 置空
  file.value = undefined
  msgs.value = []
  isOk.value = false
  emits('afterClose')
}

function open() {
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    width="640px"
    title="计量器具导入"
    :need-saving="false"
    :show-footer="false"
    class="reset"
    @close="onClose"
  >
    <p class="text-red">
      注意：导入中重复计量器具编号会覆盖处理
    </p>
    <div class="fs-14 flex items-center">
      <span class="text-secondary">上传：</span>
      <input
        ref="inputRef" type="file" placeholder="请选择文件"
        accept=".xlsx,.xls"
        @change="changeInput"
      >
      <ElButton type="primary" :disabled="!uploadable" :loading="uploading" @click="clickImportFile">
        开始导入
      </ElButton>
      <ElButton type="success" @click="clickExportFile">
        模板下载
      </ElButton>
    </div>
    <div
      class="fs-12 roll mt-4 h-[200px] border rounded px-4 py-3 line-height-[1.4]"
      :style="{
        borderColor: msgs.length > 0 ? 'var(--el-color-danger)' : 'var(--el-border-color-light)',
      }"
    >
      <p v-if="isOk" color="[var(--el-color-primary)]" class="m-0">
        导入成功
      </p>
      <div v-for="(msg, index) in msgs" :key="index" class="mb-3">
        {{ msg }}
      </div>
    </div>
  </CustomDialog>
</template>
